var user = getCookie("userName");

$(function () {
    console.log(user);
    $("#questionNameDetail").html("欢迎使用题库系统");
    var oTable = new TableInit();
    oTable.Init();
});

// XXX问卷答题情况明细
function freshTable() {
    $("#countTable").bootstrapTable('refresh');
}

function TableInit() {

    var oTableInit = {};
    //初始化Table
    oTableInit.Init = function () {
        $('#countTable').bootstrapTable({
            url: httpRequestUrl + '/getQuestionByTitle',         //请求后台的URL（*）
            method: 'POST',                      //请求方式（*）
            striped: true,                      //是否显示行间隔色
            pagination: true,                   //是否显示分页（*）
            //是否启用排序
            sortOrder: "asc",                   //排序方式
            sortStable: true,                   //是否排序
            queryParamsType: '',//默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
            dataType: 'json',
            paginationShowPageGo: true,
            showJumpto: true,
            pageNumber: 1, //初始化加载第一页，默认第一页
            queryParams: queryParams,//请求服务器时所传的参数
            sidePagination: 'server',//指定服务器端分页
            pageSize: 10,//单页记录数
            pageList: [10, 20, 30, 40],//分页步进值
            search: false, //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            silent: true,
            showRefresh: false,                  //是否显示刷新按钮
            showToggle: false,
            minimumCountColumns: 2,             //最少允许的列数
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列

            columns: [{
                checkbox: true,
                visible: false
            }, {
                field: 'id',
                title: '序号',
                align: 'center',
                formatter: function (value, row, index) {
                    return index + 1;
                }
            },
                {
                    field: 'questionType',
                    title: '题目类型',
                    align: 'center',
                    /*sortable : true*/
                },
                {
                    field: 'questionTitle',
                    title: '题目标题',
                    align: 'center',
                    /*sortable : true*/
                },
                {
                    field: 'questionOption',
                    title: '题目选项',
                    align: 'center',
                    width: '200px',
                    /*sortable : true*/
                },
                {
                    field: 'important',
                    title: '是否必答',
                    align: 'center',
                    width: '90px',
                    /*sortable : true*/
                },
                {
                    field: 'operation',
                    title: '操作',
                    width: '90px',
                    align: 'center',
                    events: operateEvents,//给按钮注册事件
                    formatter: addFunctionAlty//表格中增加按钮
                }],
            responseHandler: function (res) {
                //console.log(res);
                if (res.code === "666") {
                    var answerInfo = res.data.list;
                    console.log(answerInfo);
                    var NewData = [];
                    if (answerInfo.length) {
                        for (var i = 0; i < answerInfo.length; i++) {

                            var dataNewObj = {
                                'id': '',
                                "questionType": '',
                                'questionTitle': '',
                                "questionOption": '',
                                'important': '',
                                "uid": "",
                            };
                            dataNewObj.id = '' + i;
                            dataNewObj.uid = answerInfo[i].id;
                            var questionType = answerInfo[i].questionType;
                            if (questionType === "0") {
                                dataNewObj.questionType = '单选题';
                            } else if (questionType === "1") {
                                dataNewObj.questionType = '多选题';
                            } else if (questionType === "2") {
                                dataNewObj.questionType = '填空题';
                            } else if (questionType === "3") {
                                dataNewObj.questionType = '矩阵量表';
                            } else if (questionType === "4") {
                                dataNewObj.questionType = '量表题';
                            } else {
                                dataNewObj.questionType = '其他';
                            }
                            dataNewObj.questionTitle = answerInfo[i].questionTitle;
                            var questionOption = answerInfo[i].questionOption;
                            //将json字符串转换为数组
                            var questionOptionArr = JSON.parse(questionOption);
                            console.log(questionOptionArr);
                            //如果questionOptionArr为空
                            if (questionOptionArr.length === 0) {
                                dataNewObj.questionOption = "无选项";
                            } else {
                                //遍历数组
                                var questionOptionStr = '';
                                for (var j = 0; j < questionOptionArr.length; j++) {
                                    questionOptionStr += questionOptionArr[j].optionWord + "；";
                                }
                                //去掉最后一个分号
                                questionOptionStr = questionOptionStr.substring(0,
                                    questionOptionStr.length - 1);
                                dataNewObj.questionOption = questionOptionStr;
                            }
                            dataNewObj.important = answerInfo[i].important;
                            NewData.push(dataNewObj);
                        }
                        var data = {
                            total: res.data.total,
                            rows: NewData
                        };
                    } else {
                        var data = {
                            rows: NewData
                        };
                    }
                    return data;
                } else {
                    var data = {
                        rows: []
                    };
                    return data;
                }

            }
        });
    };

    // 得到查询的参数
    function queryParams(params) {
        var questionTitle = $("#keyWord").val();
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            pageNum: params.pageNumber,
            pageSize: params.pageSize,
            questionTitle: questionTitle,
        };
        return JSON.stringify(temp);
    }

    return oTableInit;
}

window.operateEvents = {
    //编辑
    'click #btn_count': function (e, value, row, index) {
        id = row.id;
        $.cookie('questionId', id);
    }
};

// 表格中按钮
function addFunctionAlty(value, row, index) {
    var btnText = '';
    //删除
    btnText += "<a href=\"javascript:void(0);\" onclick=\"deleteQuestion("
        + "'" + row.uid + "'"
        + ")\" style=\" color: #f00;\">删除</a>";//#f9f9f9
    return btnText;
}

function getReport() {

    //下载报告
    $("#countTable").tableExport({
        type: "excel",
        escape: "false",
        fileName: getCookie("nameOfQuestionnaire") + '答题情况明细'
    });

}

//设计问卷
function designQuestionnaire() {
    var ifDesignQuestionnaire = getCookie("ifDesignQuestionnaire");
    if (ifDesignQuestionnaire == "false") {
        layer.msg("问卷处于运行状态或问卷已发布，不可设计问卷", {icon: 2})
    } else {
        $.cookie("QuestionId", getCookie("questionId"));
        window.open('designQuestionnaire.html')
    }
}

//发送问卷
function ifSendQuestionnaire() {
    var ifSendQuestionnaire = getCookie("ifSendQuestionnaire");
    if (ifSendQuestionnaire == "false") {
        layer.msg("问卷处于未发送或暂停的状态，不可发送问卷", {icon: 2})
    } else {
        $.cookie("QuestionId", getCookie("questionId"));
        window.location.href = 'sendQuestionnaire.html';
    }
}

//回车事件
$(document).keydown(function (event) {
    if (event.keyCode === 13) {
        freshTable();
    }
});

//返回主页
function backhome() {
    window.location.href = 'myQuestionnaires.html'
}

//删除题目
function deleteQuestion(id) {
    //询问框
    layer.confirm('确定删除该题目吗？(删除后不可恢复)', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        var data = {
            "id": id
        }
        commonAjaxPost(true, "/deleteQuestion", data, function (result) {
            if (result.code === "666") {
                layer.msg(result.message, {icon: 1});
                freshTable();
            } else {
                layer.msg("删除失败", {icon: 2});
            }
        });
    }, function () {
    });
}


//批量创建
function batchCreate() {
    /*var test = "[{\"questionType\":\"0\",\"questionTitle\":\"你最近一个星期的课外活动频率如何\",\"questionOption\":[{\"lineTitle\":\"\",\"optionWord\":\"10小时以上\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"5-10小时\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"2-5小时\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"2小时以下\",\"optionGrade\":\"\"}],\"important\":\"取消必答题\"},{\"questionType\":\"2\",\"questionTitle\":\"请列举你目前的课外活动有哪些\",\"questionOption\":[],\"important\":\"必答题\"}]"
    var obj = "[{\"questionType\":\"0\",\"questionTitle\":\"完成度\",\"questionOption\":[{\"lineTitle\":\"\",\"optionWord\":\"全部完成\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"部分完成\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"未完成\",\"optionGrade\":\"\"}],\"important\":\"必答题\"},\n"
        + "{\"questionType\":\"2\",\"questionTitle\":\"你的研究课题是？\",\"questionOption\":[],\"important\":\"必答题\"},{\"questionType\":\"3\",\"questionTitle\":\"123\",\"questionOption\":[{\"lineTitle\":\"1\",\"optionWord\":\"44\",\"optionGrade\":\"\"},{\"lineTitle\":\"2\",\"optionWord\":\"23\",\"optionGrade\":\"\"},{\"lineTitle\":\"3\",\"optionWord\":\"3\",\"optionGrade\":\"\"}],\"important\":\"必答题\"},{\"questionType\":\"1\",\"questionTitle\":\"多选\",\"questionOption\":[{\"lineTitle\":\"\",\"optionWord\":\"必答题1\",\"optionGrade\":\"\"}],\"important\":\"必答题\"},\n"
        + "{\"questionType\":\"1\",\"questionTitle\":\"多选22\",\"questionOption\":[{\"lineTitle\":\"\",\"optionWord\":\"12\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"23\",\"optionGrade\":\"\"}],\"important\":\"取消必答题\"},\n"
        + "{\"questionType\":\"0\",\"questionTitle\":\"12321\",\"questionOption\":[{\"lineTitle\":\"\",\"optionWord\":\"必答题12\",\"optionGrade\":\"\"}],\"important\":\"必答题\"},\n"
        + "{\"questionType\":\"4\",\"questionTitle\":\"123123\",\"questionOption\":[{\"lineTitle\":\"\",\"optionWord\":\"很满意\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"5\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"4\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"3\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"2\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"1\",\"optionGrade\":\"\"},{\"lineTitle\":\"\",\"optionWord\":\"很不满意\",\"optionGrade\":\"\"}],\"important\":\"必答题\"}]";

  //传给后台
    data = {
      "questionList": obj
    }
    commonAjaxPost(true, "/addQuestion", data, function (data) {
    });*/
    //是否为创建题目
    deleteCookie("isCreateQuestion");
    $.cookie("isCreateQuestion", "true");
    //是否为导入题目时跳转进入的
    deleteCookie("isImportQuestion");
    $.cookie("isImportQuestion", "false");
    window.location.href = 'designQuestion.html';
}

//批量编辑
function batchEdit() {
    //是否为创建题目
    deleteCookie("isCreateQuestion");
    $.cookie("isCreateQuestion", "false");
    //是否为导入题目时跳转进入的
    deleteCookie("isImportQuestion");
    $.cookie("isImportQuestion", "false");
    //跳转到编辑页面
    window.location.href = 'designQuestion.html';
}
